package org.example;

public class Test1 {
    //leetcode 53 最大子数组和 https://leetcode.cn/problems/maximum-subarray/description/

    /**
     * 贪心，在计算连续数字和的时候，如果和为负数，那么就可以将前面部分舍弃了，从下一个位置继续求和
     * @param nums
     * @return
     */
    public int maxSubArray(int[] nums) {
        int ret = -10001,sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            ret = Math.max(ret,sum);
            sum = Math.max(sum,0);
        }
        return ret;
    }

    /**
     * 动态规划
     * @param nums
     * @return
     */
    public int maxSubArray2(int[] nums) {
        int n = nums.length,ret = nums[0];
        int[] dp = new int[n];
        dp[0] = nums[0];
        for (int i = 1; i < n; i++) {
            dp[i] = Math.max(dp[i-1] + nums[i],nums[i]);
            ret = Math.max(ret,dp[i]);
        }
        return ret;
    }

    /**
     * 动态规划空间优化
     * @param nums
     * @return
     */
    public int maxSubArray3(int[] nums) {
        int n = nums.length,ret = nums[0],prev = 0;
        for (int x : nums) {
            prev = Math.max(prev + x,x);
            ret = Math.max(ret,prev);
        }
        return ret;
    }
}
